package com.tensquare.sms.listener;

import com.aliyuncs.exceptions.ClientException;
import com.tensquare.sms.utils.SmsUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@RabbitListener(queues = "sms.checkcode")
@Component
public class SmsCheckCodeListener {

    /**
     * 注入工具类
     *
     * @param map
     */
    @Autowired
    private SmsUtils smsUtil;

    @Value("${aliyun.sms.sign_name}")
    private String sign_name;

    @Value("${aliyun.sms.template_code}")
    private String template_code;

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 消费验证码消息，向阿里云接口请求发送短信验证码
     *
     * @param map
     */
    @RabbitHandler
    public void handleSmsCheckCode(Map<String, String> map) {
        String mobile = map.get("mobile");
        // 随机验证码
        String checkcode = map.get("checkcode");
        System.out.println("手机号码：" + mobile);
        System.out.println("验证码：" + checkcode);

        /**
         * 参数模版：值为json格式的字符串
         *  如： 阿里云后台的【乐优商城测试模版】
         *  模版内容:
         * ${code}, 您正在注册乐优会员，非本人操作轻妥善保护好个人信息
         * 则占位符就是code，那键名就是code
         * 例：{"code": "123456"}
         */
        String templateParam = "{\"code\":\"" + checkcode + "\"}";
        try {
            smsUtil.sendSms(mobile, sign_name, template_code, templateParam, "123456", accessKeyId, accessKeySecret);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
